<template>
  <div class="customer-management">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchForm.startDate"
        type="date"
        placeholder="输入开始日"
        style="width: 180px; margin-right: 10px;"
      />
      <el-input
        v-model="searchForm.endDate"
        type="date"
        placeholder="输入截止日"
        style="width: 180px; margin-right: 10px;"
      />
    </div>

    <!-- 关键字搜索 -->
    <el-input
      v-model="searchForm.keyword"
      placeholder="请输入搜索内容"
      clearable
      style="width: 300px; float: right; margin-bottom: 20px;"
      @clear="handleSearch"
      @keyup.enter.native="handleSearch"
    >
      <el-button slot="append" icon="el-icon-search" @click="handleSearch"/>
    </el-input>

    <!-- 客户列表 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="customerName" label="客户昵称"/>
      <el-table-column prop="number" label="订单号"/>
      <el-table-column prop="amount" label="付款金额"/>
      <el-table-column prop="orderStatus" label="订单状态"/>
      <el-table-column prop="contactPerson" label="姓名"/>
      <el-table-column prop="contactPhone" label="联系电话"/>
      <el-table-column prop="orderTime" label="加入时间">
        <template slot-scope="scope">
          {{ scope.row.orderTime ? new Date(scope.row.orderTime).toLocaleString() : '' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column label="额外收费" width="120">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleCreateExtraOrder(scope.row)">创建订单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="创建额外订单" :visible.sync="createOrderDialogVisible" width="500px">
      <el-form :model="createOrderForm" :rules="createOrderFormRules" ref="createOrderForm" label-width="100px">
        <el-form-item label="订单名称" prop="productName">
          <el-input v-model="createOrderForm.productName" placeholder="请输入订单名称" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="createOrderForm.amount" :min="0" :step="1" style="width: 100%;" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="客户昵称">
          <el-input v-model="createOrderForm.customerName" readonly />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-input v-model="createOrderForm.orderStatus" readonly />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="createOrderForm.contactPerson" readonly />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="createOrderForm.contactPhone" readonly />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createOrderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateOrder">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="编辑客户信息" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="联系人">
          <el-input v-model="editForm.contactPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="editForm.contactPhone"></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="editForm.orderStatus" placeholder="请选择订单状态">
            <el-option label="待付款" value="待付款"></el-option>
            <el-option label="已支付" value="已支付"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[15, 25, 35, 45]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination"
    />

  </div>
</template>

<script>
import axios from '@/utils/request'

export default {
  name: 'CustomerManagement',
  data() {
    return {
      searchForm: {
        startDate: '',
        endDate: '',
        keyword: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 15,
      total: 0,
      editDialogVisible: false,
      editForm: {
        id: '',
        contactPerson: '',
        contactPhone: '',
        orderStatus: ''
      },
      createOrderDialogVisible: false,
      createOrderForm: {
        productName: '',
        amount: '',
        customerName: '',
        orderStatus: '',
        contactPerson: '',
        contactPhone: '',
        orderTime: '',
        userId: '' // 新增 userId 字段
      },
      createOrderFormRules: {
        productName: [{ required: true, message: '请输入订单名称', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async fetchData() {
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchForm.keyword || null
        }

        if (this.searchForm.startDate) {
          params.beginTime = this.searchForm.startDate + ' 00:00:00'
        }
        if (this.searchForm.endDate) {
          params.endTime = this.searchForm.endDate + ' 23:59:59'
        }

        console.log('发送请求参数：', params)
        const res = await axios.get('/admin/order/paidCustomers', { params })
        console.log('完整响应数据：', res.data)

        if (res.data && res.data.records) {
          this.tableData = res.data.records.map(record => ({
            ...record,
            orderTime: record.orderTime ? new Date(record.orderTime).toLocaleString() : '',
            createTime: record.createTime ? new Date(record.createTime).toLocaleString() : '',
            updateTime: record.updateTime ? new Date(record.updateTime).toLocaleString() : ''
          }))
          this.total = res.data.total || 0
        } else {
          this.$message.error('数据格式错误')
        }
      } catch (error) {
        console.error('获取客户数据失败：', error)
        this.$message.error('获取数据失败')
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    handleView(row) {
      this.editForm = {
        id: row.id,
        contactPerson: row.contactPerson,
        contactPhone: row.contactPhone,
        orderStatus: row.orderStatus
      }
      this.editDialogVisible = true
    },
    handleCreateExtraOrder(row) {
      this.createOrderForm = {
        productName: '',
        amount: '',
        customerName: row.customerName,
        orderStatus: row.orderStatus,
        contactPerson: row.contactPerson,
        contactPhone: row.contactPhone,
        userId: row.userId // 赋值 userId
      };
      this.createOrderDialogVisible = true;
    },
    async submitCreateOrder() {
      this.$refs.createOrderForm.validate(async (valid) => {
        if (valid) {
          try {
            // 生成18位纯数字订单号，适用于小程序long类型
            const timestamp = Date.now().toString(); // 13位
            const randomNum = Math.floor(Math.random() * 1e5).toString().padStart(5, '0'); // 5位
            const orderNo = timestamp + randomNum; // 18位纯数字

            // 生成东八区本地时间字符串，格式为 yyyy-MM-dd'T'HH:mm:ss.SSS，不带Z
            function formatDateTimeLocal(dt) {
              const date = dt ? new Date(dt) : new Date();
              const pad = n => n < 10 ? '0' + n : n;
              const ms = date.getMilliseconds().toString().padStart(3, '0');
              return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${ms}`;
            }
            const nowStr = formatDateTimeLocal();
            const today = nowStr.slice(0, 10);
            const payload = {
              number: orderNo,
              productName: this.createOrderForm.productName,
              orderAmount: Number(this.createOrderForm.amount),
              paymentMethod: '微信支付',
              orderStatus: '待支付',
              orderSource: '管理端',
              contactPerson: this.createOrderForm.contactPerson,
              contactPhone: this.createOrderForm.contactPhone,
              customerName: this.createOrderForm.customerName,
              orderTime: nowStr,
              createTime: nowStr,
              updateTime: nowStr,
              amount: Number(this.createOrderForm.amount),
              userId: this.createOrderForm.userId,
              appointmentDate: today
            };
            console.log('[创建订单] 请求参数:', payload);
            const res = await axios.post('/admin/order/upload', payload);
            console.log('[创建订单] 响应结果:', res);
            if (res && (res.code === 1 || res.data === null)) {
              // 成功仅关闭弹窗和刷新列表，不弹窗提示
              this.createOrderDialogVisible = false;
              this.fetchData();
            } else {
              console.error('[创建订单] 失败，响应:', res);
              this.$message.error((res && res.msg) || '创建订单失败');
            }
          } catch (e) {
            console.error('[创建订单] 异常:', e);
            this.$message.error('创建订单失败');
          }
        }
      });
    },
    async handleEditSubmit() {
      try {
        const res = await axios.put(`/admin/order/${this.editForm.id}`, {
          id: this.editForm.id,
          contactPerson: this.editForm.contactPerson,
          contactPhone: this.editForm.contactPhone,
          orderStatus: this.editForm.orderStatus
        })
        
        if (res.code === 1) {
          this.$message.success('更新成功')
          this.editDialogVisible = false
          this.fetchData() // 刷新列表
        } else {
          this.$message.error(res.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新客户信息失败：', error)
        this.$message.error('更新失败')
      }
    }
  },
  created() {
    this.fetchData()
  }
}
</script>

<style scoped>
.customer-management {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>